/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hps.view;

import hps.control.SimulationController;
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @author p.kielblock
 */
public class FormSimulation extends javax.swing.JFrame
{

    //Variablen fuer Simulationskontrolle
    Thread simulationThread;
    long nextTickTime;
    double secondsPerTick,
            defaultSecondsPerTick;
    boolean running;
    //Filter fuer FileChooser
    private FileFilter pngFilter;

    public FormSimulation(SimulationController sc)
    {
        this();
        roomDrawPanel1.setRoom(sc);
    }

    private FormSimulation()
    {
        initComponents();
        running = false;
        nextTickTime = System.currentTimeMillis();
        defaultSecondsPerTick = secondsPerTick = 0.3;
        pngFilter = new FileFilter()
        {
            @Override
            public boolean accept(File pathname)
            {
                return pathname.getName().toLowerCase().endsWith(".png") || pathname.isDirectory();
            }

            @Override
            public String getDescription()
            {
                return "png-Bilder(*.png)";
            }
        };
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        btnPlay = new javax.swing.JButton();
        btnPause = new javax.swing.JButton();
        btnStop = new javax.swing.JButton();
        btnForeword = new javax.swing.JButton();
        roomDrawPanel1 = new hps.view.RoomDrawPanel();
        jMenuBarSimulation = new javax.swing.JMenuBar();
        Simulation = new javax.swing.JMenu();
        jMenuItemSpeichern = new javax.swing.JMenuItem();
        jMenuItemSpeichrnUnter = new javax.swing.JMenuItem();
        SimSpeichern = new javax.swing.JMenuItem();
        jMenuItemSimulationBeenden = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Simulation");

        btnPlay.setIcon(new javax.swing.ImageIcon(getClass().getResource("/hps/view/HPS_icons/play.png"))); // NOI18N
        btnPlay.setFocusable(false);
        btnPlay.setMaximumSize(new java.awt.Dimension(40, 40));
        btnPlay.setMinimumSize(new java.awt.Dimension(40, 40));
        btnPlay.setPreferredSize(new java.awt.Dimension(40, 40));
        btnPlay.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnPlayActionPerformed(evt);
            }
        });

        btnPause.setIcon(new javax.swing.ImageIcon(getClass().getResource("/hps/view/HPS_icons/pause.png"))); // NOI18N
        btnPause.setMaximumSize(new java.awt.Dimension(40, 40));
        btnPause.setMinimumSize(new java.awt.Dimension(40, 40));
        btnPause.setPreferredSize(new java.awt.Dimension(40, 40));
        btnPause.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnPauseActionPerformed(evt);
            }
        });

        btnStop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/hps/view/HPS_icons/stop.png"))); // NOI18N
        btnStop.setFocusable(false);
        btnStop.setMaximumSize(new java.awt.Dimension(40, 40));
        btnStop.setMinimumSize(new java.awt.Dimension(40, 40));
        btnStop.setPreferredSize(new java.awt.Dimension(40, 40));
        btnStop.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnStopActionPerformed(evt);
            }
        });

        btnForeword.setIcon(new javax.swing.ImageIcon(getClass().getResource("/hps/view/HPS_icons/forward.png"))); // NOI18N
        btnForeword.setMaximumSize(new java.awt.Dimension(40, 40));
        btnForeword.setMinimumSize(new java.awt.Dimension(40, 40));
        btnForeword.setPreferredSize(new java.awt.Dimension(40, 40));
        btnForeword.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnForewordActionPerformed(evt);
            }
        });

        roomDrawPanel1.setBackground(new java.awt.Color(255, 255, 255));
        roomDrawPanel1.setAutoscrolls(true);
        roomDrawPanel1.setLayout(new java.awt.GridBagLayout());

        Simulation.setText("Simulation");

        jMenuItemSpeichern.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItemSpeichern.setText("Simulation speichern");
        jMenuItemSpeichern.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jMenuItemSpeichernActionPerformed(evt);
            }
        });
        Simulation.add(jMenuItemSpeichern);

        jMenuItemSpeichrnUnter.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        jMenuItemSpeichrnUnter.setText("Simulation speichern unter");
        jMenuItemSpeichrnUnter.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jMenuItemSpeichrnUnterActionPerformed(evt);
            }
        });
        Simulation.add(jMenuItemSpeichrnUnter);

        SimSpeichern.setText("Stand als Bild speichern");
        SimSpeichern.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                SimSpeichernActionPerformed(evt);
            }
        });
        Simulation.add(SimSpeichern);

        jMenuItemSimulationBeenden.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        jMenuItemSimulationBeenden.setText("Beenden");
        jMenuItemSimulationBeenden.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jMenuItemSimulationBeendenActionPerformed(evt);
            }
        });
        Simulation.add(jMenuItemSimulationBeenden);

        jMenuBarSimulation.add(Simulation);

        setJMenuBar(jMenuBarSimulation);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(btnPlay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnPause, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnStop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnForeword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(408, 532, Short.MAX_VALUE))
            .addComponent(roomDrawPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnPlay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnStop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnForeword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnPause, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(roomDrawPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 694, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItemSpeichrnUnterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemSpeichrnUnterActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItemSpeichrnUnterActionPerformed

    private void jMenuItemSimulationBeendenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemSimulationBeendenActionPerformed
        dispose();
    }//GEN-LAST:event_jMenuItemSimulationBeendenActionPerformed

    private void jMenuItemSpeichernActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemSpeichernActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItemSpeichernActionPerformed

    private void btnStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStopActionPerformed
        running = false;
    }//GEN-LAST:event_btnStopActionPerformed

    private void btnPauseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPauseActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnPauseActionPerformed

    private void btnForewordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnForewordActionPerformed
        secondsPerTick /= 2;
    }//GEN-LAST:event_btnForewordActionPerformed

    private void btnPlayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPlayActionPerformed
        secondsPerTick = defaultSecondsPerTick;
        if (!running)
        {
            simulationThread = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    simulationThreadTask();
                }
            });
            running = true;
            simulationThread.start();
        }
   }//GEN-LAST:event_btnPlayActionPerformed

    private void SimSpeichernActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_SimSpeichernActionPerformed
    {//GEN-HEADEREND:event_SimSpeichernActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.setAcceptAllFileFilterUsed(false);
        fc.setFileFilter(pngFilter);

        if (fc.showDialog(this, "Speichern") == JFileChooser.OPEN_DIALOG)
        {
            try
            {
                roomDrawPanel1.getRoom().saveImageTo(fc.getSelectedFile().getAbsolutePath());
            }
            catch (IOException e)
            {
                JOptionPane.showMessageDialog(this, "Fehler beim Öffnen der Datei. Datei ist möglicherweise bereits vorhanden und geöffnet.");
            }
        }
    }//GEN-LAST:event_SimSpeichernActionPerformed

    /**
     * Methode, die vom Simulationsthread ausfuehren soll
     */
    private void simulationThreadTask()
    {
        long diff;
        while ((running) && (simulationThread == Thread.currentThread()))
        {
            nextTickTime = System.currentTimeMillis() + (long) (secondsPerTick * 1000);
            ((SimulationController) roomDrawPanel1.getRoom()).iterate();
            diff = nextTickTime - System.currentTimeMillis();
            if (diff > 0)
            {
                try
                {
                    Thread.sleep(diff);
                }
                catch (InterruptedException e)
                {
                }
            }
            if (((SimulationController) roomDrawPanel1.getRoom()).simulationEnded())
            {
                JOptionPane.showMessageDialog(this, "Die Simulation wurde abgeschlossen!", "Simulationsende", JOptionPane.INFORMATION_MESSAGE);
                JFileChooser chooser = new JFileChooser();
                chooser.setAcceptAllFileFilterUsed(false);
                chooser.setFileFilter(new FileFilter()
                {
                    @Override
                    public boolean accept(File pathname)
                    {
                        return pathname.getName().toLowerCase().endsWith(".hps_stat") || pathname.isDirectory();
                    }

                    @Override
                    public String getDescription()
                    {
                        return "HPS-Statistik(*.hps_stat)";
                    }
                });
                if (chooser.showDialog(this, "Speichern") == JFileChooser.APPROVE_OPTION)
                {
                    try
                    {
                        ((SimulationController) roomDrawPanel1.getRoom()).writeStat(chooser.getSelectedFile().getAbsolutePath());
                    }
                    catch (IOException e)
                    {
                        JOptionPane.showMessageDialog(this, "Fehler beim Öffnen der Datei. Datei ist möglicherweise bereits vorhanden und geöffnet.");
                    }
                }
                running = false;

            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try
        {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
            {
                if ("Nimbus".equals(info.getName()))
                {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }
        catch (ClassNotFoundException ex)
        {
            java.util.logging.Logger.getLogger(FormSimulation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (InstantiationException ex)
        {
            java.util.logging.Logger.getLogger(FormSimulation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (IllegalAccessException ex)
        {
            java.util.logging.Logger.getLogger(FormSimulation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (javax.swing.UnsupportedLookAndFeelException ex)
        {
            java.util.logging.Logger.getLogger(FormSimulation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new FormSimulation().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem SimSpeichern;
    private javax.swing.JMenu Simulation;
    private javax.swing.JButton btnForeword;
    private javax.swing.JButton btnPause;
    private javax.swing.JButton btnPlay;
    private javax.swing.JButton btnStop;
    private javax.swing.JMenuBar jMenuBarSimulation;
    private javax.swing.JMenuItem jMenuItemSimulationBeenden;
    private javax.swing.JMenuItem jMenuItemSpeichern;
    private javax.swing.JMenuItem jMenuItemSpeichrnUnter;
    private hps.view.RoomDrawPanel roomDrawPanel1;
    // End of variables declaration//GEN-END:variables
}
